package org.jivesoftware.openfire.dynamic;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.jivesoftware.database.SequenceManager;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.container.Plugin;
import org.jivesoftware.openfire.container.PluginManager;
import org.jivesoftware.openfire.interceptor.InterceptorManager;
import org.jivesoftware.openfire.interceptor.PacketInterceptor;
import org.jivesoftware.openfire.interceptor.PacketRejectedException;
import org.jivesoftware.openfire.session.Session;
import org.jivesoftware.openfire.user.UserManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.JID;
import org.xmpp.packet.Message;
import org.xmpp.packet.Packet;
import org.jivesoftware.openfire.dynamic.*;


public class DynamicPlugin implements PacketInterceptor, Plugin{
	private static final Logger log = LoggerFactory.getLogger(DynamicPlugin.class);
	 private static PluginManager pluginManager;
    private static  DbDynamicManager dynamicManager;
    private InterceptorManager interceptorManager;
    private static String questionReceiver = "question";
    private static String answerReceiver = "answer";
    public DynamicPlugin(){
        interceptorManager = InterceptorManager.getInstance();
        dynamicManager = DbDynamicManager.getInstance();
    }
	@Override
	public void initializePlugin(PluginManager manager, File pluginDirectory) {
		// TODO Auto-generated method stub
		 interceptorManager.addInterceptor(this);
         pluginManager = manager;
         log.debug("dynamic plugin init success");
	}

	@Override
	public void destroyPlugin() {
		// TODO Auto-generated method stub
		interceptorManager.removeInterceptor(this);
        log.debug("dynamic plugin destroy success");
	}

	@Override
	public void interceptPacket(Packet packet, Session session,
			boolean incoming, boolean processed) throws PacketRejectedException {
		// TODO Auto-generated method stub
		
         JID recipient = packet.getTo();
         if (recipient != null) {
             String username = recipient.getNode();
             if (username == null || !UserManager.getInstance().isRegisteredUser(recipient)) {
                 return;
             } else if (!XMPPServer.getInstance().getServerInfo().getXMPPDomain().equals(recipient.getDomain())) {
                 return;
             } else if ("".equals(recipient.getResource())) {
             }
         }
         this.doAction(packet, incoming, processed, session);
	}
	private void doAction(Packet packet, boolean incoming, boolean processed,
			Session session) {
		// TODO Auto-generated method stub
		Packet copyPacket = packet.createCopy();
		  if (packet instanceof Message) {		
	             Message message = (Message) copyPacket;
	             if(message.getType()==Message.Type.chat){//single
	            	 log.debug("debug","single chat"+message.toXML());
	             }
               if (processed || !incoming) {
                   return;
               }
               if (incoming) {       
                   JID recipient = message.getTo();
                   String receiver = recipient.getNode();
                   if(receiver.equals(questionReceiver)){
                	   dynamicManager.addQuestion(getQuesion(packet, incoming, session));
                   }
                   else if(receiver.equals(answerReceiver)){
                	   dynamicManager.addAnswer(getAnswer(packet, incoming, session));
                   }
  	         } 
          
		  }
	}
	private QuestionBean getQuesion(Packet packet, boolean incoming,
			Session session) {
		// TODO Auto-generated method stub
		   Message message = (Message) packet;
		   QuestionBean question = new QuestionBean();
		   JID jid = session.getAddress();
		   question.setPublisher(jid.getNode());
		   SimpleDateFormat df = new SimpleDateFormat("MM-dd HH:mm");
	         String publishTime= df.format(new Date());//
		   question.setPublishTime(publishTime);
		   question.setQuestionContent(message.getBody());
		return question;
	}
	private AnswerBean getAnswer(Packet packet, boolean incoming,
			Session session) {
		// TODO Auto-generated method stub
		   Message message = (Message) packet;
		   AnswerBean answer= new AnswerBean();
		   JID jid = session.getAddress();
		   answer.setPublisher(jid.getNode());
		   //
		   SimpleDateFormat df = new SimpleDateFormat("MM-dd HH:mm");
	         String publishTime= df.format(new Date());
	         answer.setPublishTime(publishTime);
	         //
	         String idWithContent = message.getBody();
	         int index= idWithContent.indexOf("#");
	         String questionID= idWithContent.substring(0,index);
	         String answerContent =idWithContent.substring(index+1,idWithContent.length());
	         int questionId = Integer.parseInt(questionID);
	         //
	         answer.setQuestionId(questionId);
	         answer.setQuestionContent(answerContent);
		return answer;
	}


}
